<template>
  <common-modal
    ref="modalRef"
    v-bind="attrs"
    @sure="search"
    @cancel="handleCancel"
    @before-close="reset"
    @open="handleOpen"
  >
    <el-form
      label-width="110px"
      :rules="rules"
      ref="formRef"
      :inline="false"
      :model="formData"
    >
      <el-form-item label="媒体名称：" prop="mediaName">
        <el-input
          v-model="formData.mediaName"
          placeholder="请输入媒体名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="媒体标识：" prop="mediaLogo">
        <el-input
          v-model="formData.mediaLogo"
          placeholder="请输入媒体标识"
          clearable
        />
      </el-form-item>
      <el-form-item label="管理后台：" prop="manageUrl">
        <el-input
          v-model="formData.manageUrl"
          placeholder="请输入管理后台"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态：" prop="state">
        <el-radio-group v-model="formData.state">
          <el-radio label="0">禁用</el-radio>
          <el-radio label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </common-modal>
</template>
<script>
export default {
  inheritAttrs: false,
};
</script>
<script setup>
import { reactive, useAttrs, ref } from "vue";
import commonModal from "@/components/commonModal.vue";
import useForm from "@/hooks/useForm";
import { AddMedia, EditMedia } from "@/apis/media";
import { ElMessage } from "element-plus";
const props = defineProps({
  type: {
    type: String,
    default: "add",
  },
  curForm: {
    type: [Object, String],
    default: () => ({}),
  },
});
const attrs = useAttrs();
const formData = reactive({
  mediaName: "",
  mediaLogo: "",
  manageUrl: "",
  state: "1",
});
const modalRef = ref(null);
// 确定
const handleSure = async () => {
  const optionApi = props.type === 'add' ? AddMedia : EditMedia
  await optionApi({ ...formData });
  ElMessage.success({
    message: "操作成功",
    type: "success",
  });
  emits("success");
  handleCancel();
};
const { formRef, search, reset } = useForm(handleSure);
const rules = {
  mediaName: [{ required: true, message: "请输入媒体名称" }],
  mediaLogo: [{ required: true, message: "请输入媒体标识" }],
  state: [{ required: true, message: "请选择状态" }],
};

// 取消 关闭弹窗
const handleCancel = () => {
  modalRef.value?.close();
};

// 确定
const emits = defineEmits(["success"]);

// 打开弹窗
const handleOpen = () => {
  const { type, curForm } = props;
  if (type === "add") {
    Object.assign(formData, {
      mediaName: "",
      mediaLogo: "",
      manageUrl: "",
      state: "1",
    });
  } else {
    Object.assign(formData, curForm);
  }
};
</script>
